package com.study.commen.utils;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;

import java.util.concurrent.atomic.AtomicInteger;

public class TintUiUtils {


    public static final CharSequence TRUNCATE_END = "...";

    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);

    private static int sScreenWidth = 0;
    private static int sScreenHeight = 0;
    private static float sDensity = 0F;

    private TintUiUtils() {

    }


    /**
     * 转换 dp -> px
     */
    public static int dp2px(int dp) {
        return (int) (Utils.getApp().getResources().getDisplayMetrics().density * dp + 0.5F);
    }

    /**
     * 转换 px -> dp
     */
    public static int px2dp(int px) {
        return (int) (px / Utils.getApp().getResources().getDisplayMetrics().density + 0.5F);
    }

    /**
     * 获取屏幕宽度
     */
    public static int getScreenWidth() {
        if (Utils.getApp() == null) {
            return sScreenWidth;
        }

        if (sScreenWidth == 0) {
            final DisplayMetrics displayMetrics = new DisplayMetrics();
            final WindowManager wm = getWindowManager();
            wm.getDefaultDisplay().getMetrics(displayMetrics);
            sScreenWidth = displayMetrics.widthPixels;
        }
        return sScreenWidth;
    }

    /**
     * 获取屏幕高度
     */
    public static int getScreenHeight() {
        if (Utils.getApp() == null) {
            return sScreenHeight;
        }

        if (sScreenHeight == 0) {
            final DisplayMetrics displayMetrics = new DisplayMetrics();
            final WindowManager wm = getWindowManager();
            wm.getDefaultDisplay().getMetrics(displayMetrics);
            sScreenHeight = displayMetrics.heightPixels;
        }
        return sScreenHeight;
    }

    /**
     * 获取屏幕密度
     */
    public static float getDensity() {
        if (Utils.getApp() == null) {
            return sDensity;
        }

        if (sDensity == 0F) {
            final DisplayMetrics displayMetrics = new DisplayMetrics();
            final WindowManager wm = getWindowManager();
            wm.getDefaultDisplay().getMetrics(displayMetrics);
            sDensity = displayMetrics.density;
        }
        return sDensity;
    }

    public static WindowManager getWindowManager() {
        if (Utils.getApp() == null) {
            return null;
        }
        return (WindowManager) Utils.getApp()
                .getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
    }


    public static void applyEllipsizeEndCompat(final TextView textView) {
        applyEllipsizeEndCompat(textView, false);
    }

    /**
     * 解决 maxline 与 ellipsize 的冲突
     * 截取超出内容，尾部替换省略号
     * 每次更新 text 的时候都需要调用
     * TODO 后续可以考虑兼容 ellipsize start / middle , 一般没有需求
     */
    public static void applyEllipsizeEndCompat(final TextView textView, final boolean filterBreak) {
        if (textView == null) {
            return;
        }

        textView.post(new Runnable() {
            @Override
            public void run() {
                if (filterBreak) {
                    String str = textView.getText().toString();
                    String s = str.replace("\n", "");
                    textView.setText(s);
                }
                final int maxLines = textView.getMaxLines();
                if (textView.getLineCount() > maxLines) {
                    // 获取第 maxline 行 最后字符的 offset
                    final int line = textView.getLayout().getLineEnd(maxLines - 1);
                    if (line <= TRUNCATE_END.length()) {
                        // 极端情况，一行宽度只能容纳一个字符, 一般不需要考虑
                        return;
                    }
                    // CharSequence 是为了兼容 spannable 或者特殊字符, 如 emoji 等效果
                    CharSequence text = textView.getText();
                    try {
                        // 减去 省略号 占用 3 个字符长度
                        text = text.subSequence(0, line - TRUNCATE_END.length());
                        textView.setText(text);
                        textView.append(TRUNCATE_END);
                    } catch (Exception e) {
                        // 如果截取失败，不做替换
                    }
                }
            }
        });
    }

    @SuppressLint("NewApi")
    public static int generateViewId() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
            for (; ; ) {
                final int result = sNextGeneratedId.get();
                // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
                int newValue = result + 1;
                if (newValue > 0x00FFFFFF) {
                    // Roll over to 1, not 0.
                    newValue = 1;
                }
                if (sNextGeneratedId.compareAndSet(result, newValue)) {
                    return result;
                }
            }
        } else {
            return View.generateViewId();
        }
    }

    @ColorInt
    public static int parseColor(String colorStr) {
        return parseColor(colorStr, Color.WHITE);
    }

    @ColorInt
    public static int parseColor(String colorStr, @ColorInt int defaultColor) {
        if (TextUtils.isEmpty(colorStr)) {
            return defaultColor;
        }

        try {
            if (colorStr.charAt(0) == '#') {
                return Color.parseColor(colorStr);
            } else {
                return Color.parseColor(String.format("#%s", colorStr));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return defaultColor;
        }
    }

    public static boolean isColorDarker(@ColorInt int color) {
        final int r = Color.red(color);
        final int g = Color.green(color);
        final int b = Color.blue(color);
        final double darkness = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
        if (darkness > 0.5) {
            // It's a light color
            return false;
        } else {
            // It's a dark color
            return true;
        }
    }

    public static Drawable tintDrawableCompat(@DrawableRes int drawableRes,
                                              @ColorRes int colorStateList) {
        return tintDrawableCompat(ContextCompat.getDrawable(Utils.getApp(), drawableRes).mutate(),
                ContextCompat.getColorStateList(Utils.getApp(), colorStateList));
    }

    public static Drawable tintDrawableCompat(@DrawableRes int drawableRes,
                                              ColorStateList colorStateList) {
        return tintDrawableCompat(ContextCompat.getDrawable(Utils.getApp(), drawableRes).mutate(), colorStateList);
    }

    /**
     * drawable tint compat
     * 兼容着色效果
     */
    public static Drawable tintDrawableCompat(Drawable drawable, ColorStateList colorStateList) {
        if (drawable == null) {
            return null;
        }
        try {
            final Drawable wrap = DrawableCompat.wrap(drawable.mutate().getConstantState().newDrawable());
            DrawableCompat.setTintList(wrap, colorStateList);
            return wrap;
        } catch (NullPointerException e) {
            return null;
        }
    }


}
